import json
import re

from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from django.http.response import HttpResponseBadRequest,HttpResponse, JsonResponse

from apps.users.models import User
from utils.response_code import RETCODE


class RegisterView(View):
    def get(self,request):

        return render(request,'register.html')


    def post(self,request):
        # 1接收数据
        username=request.POST.get('username')
        password=request.POST.get('password')
        password2=request.POST.get('password2')
        mobile=request.POST.get('mobile')
        # 2验证数据
        # 四个参数必须有值
        if not all([username,password,password2,mobile]):
            # 说明有变量为空值
            return HttpResponseBadRequest('参数不全')

        import re
        if not re.match(r'[a-zA-Z0-9]{5,20}',username):
            return HttpResponseBadRequest('用户名不满足条件')

        if not re.match(r'[a-zA-Z0-9]{8,20}',password):
            return HttpResponseBadRequest('密码不符合规则')

        if password2 != password:
            return HttpResponseBadRequest('密码不一致')

        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return HttpResponseBadRequest('手机号错误')

        # 用user保存信息
        user = User.objects.create_user(username=username,
                                 password=password,
                                 mobile=mobile)

        from django.contrib.auth import login
        # 使用user保持登录状态
        login(request,user)



        return redirect(reverse('contents:index'))
        return HttpResponse('ok')



    pass


class RegisterUsernameCounView(View):
    def get(self,request,username):
        count=User.objects.filter(username=username).count()
        return JsonResponse({'count':count})
        pass

class LoginView(View):
    def get(self,request):
        return render(request,'login.html')


    def post(self,request):
        # 接收数据
        username=request.POST.get('username')
        password=request.POST.get('pwd')
        remebered=request.POST.get('remebered')
        # 验证数据
        if not all([username,password]):
            return HttpResponseBadRequest('参数不全')
        # 用户名，密码是否符合正则　　此处省略

        # 再判断用户名和密码是否匹配一致
        from django.contrib.auth import authenticate
        from django.contrib.auth.backends import ModelBackend
        # 认证成功返回User对象
        # 认证失败返回None
        # authenticate
        user = authenticate(username=username,password=password)
        if user is None:
            return HttpResponseBadRequest('用户名或密码错误')
        # 记住登录
        login(request,user)
        if remebered == 'on':
            # 记住登录
            request.session.set_expiry(None)
        else:
            # 不记住登陆
            request.session.set_expiry(0)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username',user.username,max_age=3600)
        return response


class LogoutView(View):
    def get(self,request):

        # request.session.flush()  # 清除session信息 删除用户登陆状态
        # from django.contrib.auth import logout  使用django自带函数实现删除session信息功能
        from django.contrib.auth import logout
        logout(request)

        response = redirect(reverse('contents:index'))

        # response.set_cookie('username',None,max_age=0)使用这个方法也可以，原理相同
        response.delete_cookie('username')

        return response

'''
１　登录用户才可以访问用户中心
２　可以使用已学的只是来实现判断
３　使用系统的mixin
４　使用系统的需要修改mixin的默认跳转url
'''
from django.contrib.auth.mixins import LoginRequiredMixin

class UserCenterInfoView(LoginRequiredMixin,View):
    def get(self,request):
        # request.user　请求中有用户的信息
        # is_authenticated 判断用户是否为登陆用户
        # 登陆用户为True
        # 未登录用户为False
        # if request.user.is_authenticated:
        #     # render会自动到templates中找模板
        #     return render(request,'user_center_info.html')
        # else:
        #     return redirect(reverse('users:login'))

        # 1 获取／组织登陆用户信息
        context = {
            'username':request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active,
        }


        return render(request, 'user_center_info.html',context=context)



class EmailView(LoginRequiredMixin,View):
    def put(self,request):
        # 必须是登陆用户才能访问
        #  １　接收　axios
        body=request.body
        body_str=body.decode()
        data=json.loads(body_str)
        # 2 验证
        email=data.get('email')
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$',email):
            return JsonResponse({'code':RETCODE.PARAMERR,'errmsg':'邮箱不符合规则'})
        # 3 更新数据

        # 获取数据
        request.user.email=email
        # requset.user.save 添加到数据库
        request.user.save()

        # 4 给邮箱发送激活连接

        # 5 返回相应
        return JsonResponse({'code':RETCODE.OK,'errmsg':'ok'})


class UserCenterSiteView(View):
    def get(self,request):

        return render(request,'user_center_site.html')







